<?php
// Backend only
require 'includes/config.php';
require 'includes/auth.php';
require 'includes/sanitize.php';
$data = sanitize($_GET);
// Check if user tries to join a team
if(isset($_GET['joinleague'])){
	// Request to join the given league
	$request = new makeRequest($backend.'api.php', 'POST','method=joinleague&auid='.$_SESSION['uid'].
	'&accesstoken='.$_SESSION['accesstoken'].'&leagueid='.$data['joinleague']);
	$tmp = $request->makeRequest();
	$rbody = $tmp[0];
	$obj = json_decode($rbody);
	$http_code = $tmp[1];
	// Check so there is no errors
	if($http_code == 200){
		$info = "You successfully joined the league!";
	}else{
		$info = "You failed to join the league!";
	}
}
$msg = "";
// Request to backend to get information about the users teams
$request = new makeRequest($backend.'api.php?method=league&auid='.$_SESSION['uid'].'&accesstoken='
.$_SESSION['accesstoken'], 'GET');
$tmp = $request->makeRequest();
$rbody = $tmp[0];
$obj = json_decode($rbody);
$http_code = $tmp[1];
// Check so there is no errors
if($http_code == 200 && $obj[0]->{'id'} != ""){
	// Beginning of the table
	$msg.="<table border='1'><tr>
	<th>League name</th>
	<th>League description</th>
	<th>Draft limit</th>
	<th>Money limit</td>
	<th>Player limit</th>
	<th>League owner</th>
	<th>League opento</th></tr>";
	// Insert all player ids to array
	$playerids= array($value->{'lw'},$value->{'c'},$value->{'rw'},$value->{'rd'},$value->{'ld'},$value->{'g'});
	// Resolv player id to player name
	foreach($obj as &$value){
		// Resolv user id to username
		$request = new makeRequest($backend.'api.php?method=user&id='.$value->{'owner'}, 'GET');
		$tmp = $request->makeRequest();
		$rbody = $tmp[0];
		$obj2 = json_decode($rbody);
		$http_code = $tmp[1];
		// Check so it's successfull
		if($http_code == 200){
			// Resolv securitylevel to a understandable string
			switch ($value->{'securitylevel'}){
				case 1:
					$level = "Open for all";
					break;
				case 2:
					$level = "Friends only";
					break;
				case 3:
					$level = "Invite only";
					break;
			}
			// Insert information about the league into table
			$msg.="<tr>
			<td><a href='teamscoreboard.php?leagueid=".$value->{'id'}."'>".$value->{'name'}."</a></td>
			<td>".$value->{'description'}."</td>
			<td>".$value->{'draftlimit'}."</td>
			<td>".$value->{'moneylimit'}."</td>
			<td>".$value->{'playerlimit'}."</td>
			<td>".$obj2[0]->{'username'}."</td>
			<td>".$level."</td></tr>";

		}
	}
	$msg.="</table>";
}else{
	$msg = "No leagues to display";
}
require 'includes/header.php';
require 'includes/topmenu.php';
echo '<div id="kaka">';
require 'includes/sidemenu.php';
echo '<div id="content">';
if(isset($info)){ // Check if there is some info about league join to display
	echo $info;
}
if($msg!=""){ // Check if there is a table with leagues to display
	echo $msg;
}else{
	echo "You don't own any league";
}
echo '<div id="info">';
echo '</div>';
require 'includes/footer.php';
?>

</body>
</html>
